<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;

class TtsController extends Controller
{
    protected $host = 'openspeech.bytedance.com';

    /**
     * 文本转语音
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function textToSpeech(Request $request)
    {
        try {
            $request->validate([
                'text' => 'required|string',
                'voice_type' => 'required|string',
                'speed_ratio' => 'numeric|min:0.5|max:2.0',
                'volume_ratio' => 'numeric|min:0.5|max:2.0',
                'pitch_ratio' => 'numeric|min:0.5|max:2.0',
            ]);

            $response = Http::withHeaders([
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer;' . config('services.bytedance.token'),
            ])->post("https://{$this->host}/api/v1/tts", [
                'app' => [
                    'appid' => config('services.bytedance.appid'),
                    'token' => config('services.bytedance.token'),
                    'cluster' => 'volcano_icl',
                ],
                'user' => [
                    'uid' => $request->user_id ?? Str::random(16),
                ],
                'audio' => [
                    'voice_type' => $request->voice_type,
                    'encoding' => 'mp3',
                    'speed_ratio' => $request->speed_ratio ?? 1.0,
                    'volume_ratio' => $request->volume_ratio ?? 1.0,
                    'pitch_ratio' => $request->pitch_ratio ?? 1.0,
                ],
                'request' => [
                    'reqid' => Str::uuid(),
                    'text' => $request->text,
                    'text_type' => 'plain',
                    'operation' => 'query',
                    'with_frontend' => 1,
                    'frontend_type' => 'unitTson'
                ]
            ]);

            if (!$response->successful()) {
                throw new \Exception('语音合成请求错误: ' . $response->body());
            }

            $responseData = $response->json();
            
            if (!isset($responseData['data'])) {
                throw new \Exception('语音合成返回数据格式错误');
            }

            // 生成文件名
            $fileName = 'tts_' . time() . '_' . Str::random(8) . '.mp3';
            
            // 保存音频文件
            $audioData = base64_decode($responseData['data']);
            Storage::disk('public')->put('tts/' . $fileName, $audioData);

            return response()->json([
                'success' => true,
                'data' => [
                    'file_name' => $fileName,
                    'file_url' => Storage::disk('public')->url('tts/' . $fileName),
                    'original_response' => $responseData
                ],
                'message' => '语音合成成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 从base64数据生成MP3文件
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function generateMp3FromBase64(Request $request)
    {
        try {
            $request->validate([
                'base64_data' => 'required|string',
            ]);

            // 生成文件名
            $fileName = 'tts_' . time() . '_' . Str::random(8) . '.mp3';
            
            // 保存音频文件
            $audioData = base64_decode($request->base64_data);
            Storage::disk('public')->put('tts/' . $fileName, $audioData);

            return response()->json([
                'success' => true,
                'data' => [
                    'file_name' => $fileName,
                    'file_url' => Storage::disk('public')->url('tts/' . $fileName)
                ],
                'message' => 'MP3文件生成成功'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
} 